<script setup>
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { showToast, showConfirmDialog } from "vant";
import { debounce } from "@/utils/debounce"
import { useI18n } from "vue-i18n";
import {
  getOrderListAPI,
  DelOrderListAPI,
  fialOrderAPI,
  completedItemAPI,
  getMyOrderByUidAPI
} from "@/server/api/itemOrders";
import {
  getLiveOrderListByShopIdAPI,
  DelShopOrderAPI,
  failOrderShopAPI,
  completedOrderAPI,
  getLiveOrderListByShopNameAPI
} from "@/server/api/shopOrder";

import { useUseStore } from "@/stores/user";
import { ItemShopStore } from "@/stores/ItemAnShop";
import { orderStatus } from "@/stores/payStore";

import { ToastFun } from "@/hook/toast";
const { t } = useI18n();
const ItemShop = ItemShopStore();
const useStore = useUseStore();

// 定义全部订单数据
const allOrdersList = ref([]);
const page = ref(1);
const loading = ref(false);
const finished = ref(false);
const router = useRouter();
const limit = ref(10);

const status = ref(-1)
const start = ref(1) //第几页
const size = ref(8) //每页数量
const searchQuery = ref(""); // 搜索框内容

// 获取shop订单接口方法
const getOrderListByShopId = async (PageData) => {
  try {

    ToastFun("Loading", { duration: 0, msg: t("hotelPage.message"), position: "center" });
    const res = await getLiveOrderListByShopIdAPI(PageData);
    if (res.data.code === 200) {
      let data = res.data.data;
      if (data.length < size.value) {
        finished.value = true;
      }
      else {
        const newHotelList = data.map((item) => ({
          ...item
        }));
        allOrdersList.value.push(...newHotelList);
        console.log("shop订单列表", allOrdersList.value);
        loading.value = false;
        // 初始化订单的倒计时
        allOrdersList.value.forEach((item) => {
          if (item.orderStatus == 0) {  // 只有在待支付状态时才需要倒计时
            updateRemainingTime(item);  // 更新每个订单的剩余时间
            startCountdown(item);  // 启动倒计时
          }
        });
        ToastFun("success", { msg: t("item.details.OrderAcquisitionSuccess"), position: "bottom", duration: 2000 });
      }
    } else {
      // 如果返回状态码不为200，显示失败提示
      ToastFun("fail", { msg: res.data.message || t("item.details.OrderAcquisitionFailure"), position: "bottom", duration: 2000 });
    }
  } catch (error) {
    console.error("Error fetching orders:", error);
    ToastFun("fail", { msg: t("item.details.OrderAcquisitionFailure"), position: "bottom", duration: 2000 });
  } finally {
    ToastFun("close")
  }
};

//实体店根据商品名查找订单接口
const getLiveOrderListByShopName = async (data) => {
  const res = await getLiveOrderListByShopNameAPI(data);
  if (res.data.code === 200) {
    finished.value = true;
    loading.value = false;
    // 清空原有的订单列表，然后将新的订单数据赋值给 allOrdersList
    allOrdersList.value = res.data.data;
    allOrdersList.value.forEach((item) => {
      if (item.orderStatus == 0) {  // 只有在待支付状态时才需要倒计时
        updateRemainingTime(item);  // 更新每个订单的剩余时间
        startCountdown(item);  // 启动倒计时
      }
    });
  }
};

// 定义Nav导航栏数据
const NavList = ref([
  { title: "me.order.allOrders" },
  { title: "me.order.pending" },
  { title: "order.successful" },
]);

// 定义切换条件
const stateIndex = ref(0);

// 定义tab切换方法
const OrderListDataFun = (index) => {
  if (index !== undefined) {
    stateIndex.value = index;
  }
  let OrderList = [];
  // console.log("索引", index);

  switch (stateIndex.value) {
    case 1:
      OrderList = allOrdersList.value.filter((item) => item.orderStatus == 0);
      break;
    case 2:
      OrderList = allOrdersList.value.filter((item) => item.orderStatus != 0);
      break;
    default:
      OrderList = allOrdersList.value;
  }
  // console.log(OrderList.length);
  // console.log(OrderList);
  return OrderList;
};



// 定义item订单失效接口
const fialOrder = (id) => {
  const res = fialOrderAPI(id);
  console.log(res);
};

// 定义shop订单失效接口
const failOrderShop = (id) => {
  const res = failOrderShopAPI(id);
  console.log(res);
};

// 定义删除shop订单接口
const delShopOrder = async (id) => {
  const res = await DelShopOrderAPI(id);
  console.log("删除", res);
};


// 定义删除方法
const deleteOder = (id, index) => {
  console.log(id);
  ItemShop.IdtStatus == "item" ? DelOrderList(id) : delShopOrder(id);
  allOrdersList.value.splice(index, 1);
};

// 定义item订单确认方法
const completedItem = async (id) => {
  const res = await completedItemAPI(id);
  console.log(res);
};

// 定义shop订单确认方法
const completedOrder = async (id) => {
  const res = await completedOrderAPI(id);
  console.log(res);
};

// 定义确认收货方法
const comOrder = (id, index) => {
  showConfirmDialog({
    title: "确认收货",
    message: "请问确定收货吗",
  })
    .then(() => {
      // on confirm
      ItemShop.IdtStatus == "item" ? completedItem(id) : completedOrder(id);
      allOrdersList.value[index].orderStatus = 2;
    })
    .catch(() => {
      // on cancel
      console.log("取消确认");
    });
};

const onLoad = () => {
  // 异步更新数据
  if (finished.value) return;
  loading.value = true;
  const PageData = {
    orderStatus: status.value,
    userId: useStore.userId,
    shopId: null,
    currentPage: ++start.value,
    pageSize: size.value
  }
  console.log(123123);

  getOrderListByShopId(PageData);
  // finished.value = false;
  // console.log(page.value);

};

// 跳转评论页面
const goDelShipped = (item) => {
  console.log(item);
  router.push({
    path: `/DelShipped`,
    query: { OrderDetail: JSON.stringify(item) },
  });
};

// 跳转订单详情页面
const goDetail = (itemInfo) => {
  console.log(itemInfo, "shop")
  router.push({
    path: `/Detail/${itemInfo.orderId}`,
    query: { shopOrderDetail: JSON.stringify(itemInfo) },
  });

};
// 格式化时间为 HH:mm:ss
const formatTime = (ms) => {
  const minutes = String(Math.floor(ms / 60000)).padStart(2, '0'); // 获取分钟数
  const seconds = String(Math.floor((ms % 60000) / 1000)).padStart(2, '0'); // 获取秒数
  return `${minutes}:${seconds}`; // 返回格式化后的时间
};

// 定义剩余时间
const updateRemainingTime = (item) => {
  const createTime = new Date(item.createTime).getTime(); // 获取订单创建时间
  const now = Date.now(); // 当前时间
  const remainingTime = Math.max(0, createTime + 599000 - now); // 10分钟倒计时 (600000毫秒)
  item.remainingTime = remainingTime; // 更新订单的剩余时间
};

// 动态更新时间
const startCountdown = (item) => {
  // 每秒更新倒计时
  setInterval(() => {
    updateRemainingTime(item);
  }, 1000);
};

onMounted(() => {
  allOrdersList.value = [];
  start.value = 1;
  finished.value = false;
  loading.value = false;
  // 获取订单数据
  // 实体店订单获取
  const PageData = {
    orderStatus: status.value,
    userId: useStore.userId,
    shopId: null,
    currentPage: start.value,
    pageSize: size.value
  }
  getOrderListByShopId(PageData);  // 获取Shop类型的订单
});

// 防抖函数来延迟处理搜索输入
const handleSearch = debounce(() => {
  start.value = 1;
  const query = searchQuery.value.trim();
  // 如果搜索框为空，恢复为初始订单列表
  if (!query) {
    allOrdersList.value = [];
    finished.value = false;
    loading.value = false;
    const PageData = {
      orderStatus: status.value,
      userId: useStore.userId,
      shopId: null,
      currentPage: start.value,
      pageSize: size.value
    }
    getOrderListByShopId(PageData);
    return;
  }
  else {
    allOrdersList.value = [];
    finished.value = true;
    const data = {
      orderStatus: status.value,
      userId: useStore.userId,
      commodityName: query
    }
    getLiveOrderListByShopName(data);
  }
}, 300); // 300ms防抖

const handleClear = () => {
  start.value = 1;
  allOrdersList.value = [];
  finished.value = false;
  const PageData = {
    orderStatus: status.value,
    userId: useStore.userId,
    shopId: null,
    currentPage: start.value,
    pageSize: size.value
  }
  getOrderListByShopId(PageData);
}



</script>

<template>
  <van-sticky>
    <top-button-live-info :title="ItemShop.IdtStatus == 'item'
      ? $t('me.order.itemOrder')
      : $t('me.order.shopOrder')
      " :Send="ItemShop.IdtStatus == 'item' ? '' : $t('me.order.hotelOrder')">
      <template #search>
        <van-field v-model="searchQuery" placeholder="请输入商品名称" clearable left-icon="search" @input="handleSearch"
          @clear="handleClear" />
      </template>
    </top-button-live-info>

    <div class="tab_list">
      <ul>
        <li :class="{ active: stateIndex === index }" @click="OrderListDataFun(index)" v-for="(i, index) in NavList"
          :key="index">
          {{ $t(i.title) }}
        </li>
      </ul>
    </div>
  </van-sticky>

  <div class="itemCenter">
    <ul class="list">
      <van-list v-model:loading="loading" :immediate-check="false" :finished="finished"
        :finished-text="$t('shop.shopList.finish')" @load="onLoad">
        <li class="box_show" v-for="(item, index) in OrderListDataFun() " @click="goDetail(item)" :key="index">
          <van-swipe-cell>
            <div class="list_hd">
              <div class="login">
                <img v-lazy="item.shopUrl" alt="" v-if="ItemShop.IdtStatus === 'item'" />
                <span class="shop-name">
                  {{
                    ItemShop.IdtStatus === "item" ? item.shopName : item.sellerName
                  }}
                </span>
              </div>
              <div class="text_right" v-if="item.orderStatus == 1">
                {{ $t("me.order.confirming") }}
              </div>
              <div class="text_right" v-else-if="item.orderStatus == 0">
                {{ $t("me.order.toPay") }}
                <span v-if="item.remainingTime > 0">
                  {{ formatTime(item.remainingTime) }}
                </span>
                <span v-else>订单已过期</span>
              </div>
              <div class="text_right" v-else-if="item.orderStatus == 2">
                {{ $t("me.order.feedback") }}
              </div>
              <div class="text_right" v-else-if="item.orderStatus == 3">
                已过期
              </div>
              <div class="text_right" v-else-if="item.orderStatus == 4">
                {{ $t("me.order.feedbacked") }}
              </div>
            </div>
            <div class="list_ad">
              <div class="imgs" v-if="ItemShop.IdtStatus == 'item'">
                <img v-lazy="item.imagsList[0]" alt="" />
              </div>
              <div class="imgs" v-else>
                <img v-lazy="item.commodityImg" alt="" />
              </div>



              <div class="title ellipsis-2">
                {{
                  ItemShop.IdtStatus === "item"
                    ? (item.shopOrderDetail && item.shopOrderDetail[0]?.roomTypeName || 'No commodity name')
                    : item.roomTypeName
                }}
                <!-- <span >
                  {{ ItemShop.IdtStatus === "item"
                    ?  (item.shopOrderDetail && item.shopOrderDetail[0]?.commoditySpecification || 'No commodity name') : item.details }}
                </span> -->
              </div>

              <div class="introduce">
                <div class="price">
                  {{ item.transactionAmount || item.piAmount }}
                  <i>{{ item.transactionAmount ? "eCNY" : "Pi" }}</i>
                </div>
                <div class="bottom_button">
                  <div class="btn" v-if="item.orderStatus == 1" @click.stop="comOrder(item.orderId, index)">
                    {{ $t("me.order.confirm") }}
                  </div>

                  <div class="btn" @click.stop="goDetail(item)" v-if="item.orderStatus == 0">
                    {{ $t("me.order.check") }}
                  </div>

                  <div class="btn" @click.stop="
                    goDelShipped(item)
                    " v-if="item.orderStatus == 2">
                    {{ $t("me.order.feedback") }}
                  </div>
                </div>
              </div>
            </div>

            <template #right>
              <van-button square text="删除" type="danger" class="delete-button"
                @click="deleteOder(item.orderId, index)" />
            </template>
          </van-swipe-cell>
        </li>
      </van-list>
    </ul>
  </div>
</template>

<style lang="scss" scoped>
.tab_list {
  padding-top: 60rem;

  ul {
    background-color: #f5f5f5;
    display: flex;
    justify-content: space-around;
    padding: 15rem 10rem;

    li {
      font-size: 15rem;
      position: relative;
      color: #ccc;
      font-weight: 600;

      &::after {
        position: absolute;
        bottom: -10rem;
        display: none;
        content: "";
        background-color: #642e8e;
        width: 20rem;
        height: 3rem;
        left: 50%;
        transform: translateX(-50%);
        border-radius: 10rem;
      }

      &:hover {
        color: #642e8e;

        &::after {
          display: block;
          color: #642e8e;
        }
      }

      &.active {
        color: #642e8e;

        &::after {
          display: block;
        }
      }
    }
  }
}

.itemCenter {
  font-size: 14rem;
  height: 100vh;
  background-color: #f5f5f5;
  box-sizing: border-box;
  width: 100%;

  .list {
    background-color: #f5f5f5;

    li {
      box-sizing: border-box;
      margin-top: 10rem;
      background-color: #fff;
      border: 10rem solid #fff;

      :deep(.delete-button) {
        height: 100%;
      }

      .list_hd {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 20rem;
        padding: 10rem 0;
        gap: 20rem;


        .login {
          display: flex;
          align-items: center;
          flex: 1;

          min-width: 0;

          color: #000000;
          font-weight: 500;
          font-size: 16rem;


          img {
            margin-right: 10rem;
            width: 24rem;
            height: 24rem;
            /* 固定高度 */
            object-fit: cover;
            vertical-align: middle;
            border-radius: 50%;
          }

          .shop-name {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;

          }
        }

        .text_right {
          flex-shrink: 0;

          color: #642e8e;
          font-size: 16rem;
          white-space: nowrap;

          margin-left: 20rem;

        }
      }

      .list_ad {
        display: flex;
        justify-content: space-between;

        margin-top: 5rem;

        .imgs {
          width: 70rem;
          height: 70rem;
          overflow: hidden;

          border-radius: 10rem;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .title {
          margin: 0 20rem;
          width: 170rem;
          height: 72rem;
          font-size: 14rem;
          line-height: 26rem;

          display: flex;
          justify-content: space-between;
          flex-direction: column;

          >span:nth-of-type(1) {
            white-space: nowrap;
            text-overflow: ellipsis;
          }
        }

        .introduce {
          display: flex;
          flex-direction: column;
          align-items: flex-end;

          .price {
            white-space: nowrap;
            margin: 0 5rem 20rem;
            font-size: 16rem;
            font-weight: 600;
            color: rgb(0, 0, 0);

            >i {
              color: #000000;
              font-size: 12rem;
            }
          }

          .bottom_button {
            margin-left: auto;
            display: flex;

            .btn {
              padding: 2rem 20rem;
              font-size: 12rem;
              height: 30rem;
              width: 50rem;
              line-height: 30rem;
              text-align: center;
              border-radius: 20rem;
              background-color: #642e8e;
              color: #fff;
            }
          }
        }
      }
    }
  }
}
</style>
